package com.meixiang.view.wheel;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.meixiang.R;
import com.meixiang.tool.Tool;
import com.meixiang.view.wheel.mode.CityModel;
import com.meixiang.view.wheel.mode.DistrictModel;
import com.meixiang.view.wheel.mode.ProvinceModel;
import com.meixiang.view.wheel.widget.TosAdapterView;
import com.meixiang.view.wheel.widget.TosGallery;
import com.meixiang.view.wheel.widget.WheelView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 地址选择Dialog
 * author：wangzuzhen on 2016/4/5 0005 15:13.
 */
public class AddressIdsDialog extends Dialog {

    public interface AddressListener {
        public void getAddress(String address, String provinceId, String cityId, String districtId);
    }

    private Context context;
    private String title;
    private String rightTitle;
    private View view;
    private AddressListener addressListener;
    private WheelView mViewProvince = null;
    private WheelView mViewCity = null;
    private WheelView mViewDistrict = null;

    private TextView tv_right_title = null;
    private TextView mTitleTextView = null;
    private View mDecorView = null;

    private NumberAdapter provinceAdapter;
    private NumberAdapter cityAdapter;
    private NumberAdapter districtAdapter;

    private Activity mActivity;

    private List<ProvinceModel> provinceList;

    TosAdapterView.OnItemSelectedListener mListener = new TosAdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(TosAdapterView<?> parent, View view, int position, long id) {
            if (parent == mViewProvince) {
                updateCities();
            } else if (parent == mViewCity) {
                updateAreas();
            } else if (parent == mViewDistrict) {
                if (TextUtils.isEmpty(mCurrentDistrictName)) {
                    mCurrentDistrictName = "";
                    mCurrentDistrictNameIds = "";
                } else {
                    mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[position];
                    mCurrentDistrictNameIds = mDistrictDatasMapIds.get(mCurrentCityNameIds)[position];
//                mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);//邮编

                }
            }
        }

        @Override
        public void onNothingSelected(TosAdapterView<?> parent) {
        }
    };

    public AddressIdsDialog(Activity activity, Context context, List<ProvinceModel> provinceList, String title, String rightTitle, AddressListener addressListener) {
        super(context);
        this.mActivity = activity;
        this.context = context;
        this.provinceList = provinceList;
        this.addressListener = addressListener;
        this.title = title;
        this.rightTitle = rightTitle;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        view = LayoutInflater.from(context).inflate(R.layout.dialog_wheel_item, null);
        setContentView(view);
        super.onCreate(savedInstanceState);
        initProvinceDatas();
        initDialog();
        mViewProvince = (WheelView) findViewById(R.id.wheel1);
        mViewCity = (WheelView) findViewById(R.id.wheel2);
        mViewDistrict = (WheelView) findViewById(R.id.wheel3);

        mViewProvince.setScrollCycle(true);
        mViewCity.setScrollCycle(true);

        provinceAdapter = new NumberAdapter(mProvinceDatas, mProvinceDataIds);
        String[] citys = mCitisDatasMap.get(mProvinceDatas[0]);
        String[] cityIds = mCitisDatasMapIds.get(mProvinceDataIds[0]);
        cityAdapter = new NumberAdapter(citys, cityIds);
        String[] district = mDistrictDatasMap.get(citys[0]);
        String[] districtIds = mDistrictDatasMap.get(cityIds[0]);
        districtAdapter = new NumberAdapter(district, districtIds);

        mViewProvince.setAdapter(provinceAdapter);
        mViewCity.setAdapter(cityAdapter);
        mViewDistrict.setAdapter(districtAdapter);

        mViewProvince.setSelection(0, true);
        mViewCity.setSelection(0, true);
        mViewDistrict.setSelection(0, true);

        mViewProvince.setOnItemSelectedListener(mListener);
        mViewCity.setOnItemSelectedListener(mListener);
        mViewDistrict.setOnItemSelectedListener(mListener);

        mViewProvince.setUnselectedAlpha(0.5f);
        mViewCity.setUnselectedAlpha(0.5f);
        mViewDistrict.setUnselectedAlpha(0.5f);

        mDecorView = getWindow().getDecorView();

        tv_right_title = (TextView) findViewById(R.id.tv_right_title);
        mTitleTextView = (TextView) findViewById(R.id.title);
        mTitleTextView.setText(title);
        tv_right_title.setText(rightTitle);
        tv_right_title.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {//完成
                // TODO Auto-generated method stub
//                Toast.makeText(context, mCurrentProviceName + mCurrentCityName + mCurrentDistrictName, Toast.LENGTH_SHORT).show();
                if (TextUtils.isEmpty(mCurrentDistrictName)) {
                    mCurrentDistrictName = "";
                    mCurrentDistrictNameIds = "";
                }

                addressListener.getAddress(mCurrentProviceName + "，" + mCurrentCityName + "，" + mCurrentDistrictName, mCurrentProviceNameIds, mCurrentCityNameIds, mCurrentDistrictNameIds);
                dismiss();
            }
        });
    }

    private void initDialog() {
        setCancelable(false);
        getWindow().setGravity(Gravity.BOTTOM);
        getWindow().setBackgroundDrawableResource(R.color.transparent);
        int width = Tool.getWindowWith(context);
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.width = width;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        getWindow().setAttributes(params);
    }

    /**
     * 根据当前的省，更新市WheelView的信息
     */
//    int pCurrent = 0;
    private void updateCities() {
        int pCurrent = mViewProvince.getSelectedItemPosition();
//		System.out.println(pCurrent+"--------------pCurrent------------");
        mCurrentProviceName = mProvinceDatas[pCurrent];
        mCurrentProviceNameIds = mProvinceDataIds[pCurrent];
        String[] cities = mCitisDatasMap.get(mCurrentProviceName);
        String[] citieIds = mCitisDatasMapIds.get(mCurrentProviceNameIds);
        if (cities == null) {
            cities = new String[]{""};
            citieIds = new String[]{""};
        }
        cityAdapter.setData(mCitisDatasMap.get(mProvinceDatas[pCurrent]), mCitisDatasMapIds.get(mProvinceDataIds[pCurrent]));
        mViewCity.setAdapter(cityAdapter);

        updateAreas();
//		}
    }

    /**
     * 根据当前的市，更新区WheelView的信息
     */
    private void updateAreas() {
        int pCurrent = mViewCity.getSelectedItemPosition();
//		System.out.println(pCurrent+"--------------pCurrent------------");
        if (mCitisDatasMap.get(mCurrentProviceName).length >= pCurrent) {
            mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
            mCurrentCityNameIds = mCitisDatasMapIds.get(mCurrentProviceNameIds)[pCurrent];
            String[] areas = mDistrictDatasMap.get(mCurrentCityName);
            String[] areaIds = mDistrictDatasMapIds.get(mCurrentCityNameIds);
            if (areas == null || areas.length == 0) {
                areas = new String[]{""};
                areaIds = new String[]{""};
            }
            mCurrentDistrictName = areas[0];
            mCurrentDistrictNameIds = areaIds[0];
            districtAdapter.setData(areas, areaIds);
            mViewDistrict.setAdapter(districtAdapter);
        }
    }

    @Override
    public void dismiss() {
        super.dismiss();
    }


    /**
     * 所有省
     */
    protected String[] mProvinceDatas;
    protected String[] mProvinceDataIds;
    /**
     * key - 省 value - 市
     */
    protected Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
    protected Map<String, String[]> mCitisDatasMapIds = new HashMap<String, String[]>();
    /**
     * key - 市 values - 区
     */
    protected Map<String, String[]> mDistrictDatasMap = new HashMap<String, String[]>();
    protected Map<String, String[]> mDistrictDatasMapIds = new HashMap<String, String[]>();
    /**
     * key - 区 values - 邮编
     */
//    protected Map<String, String> mZipcodeDatasMap = new HashMap<String, String>();
    //区--ids
    protected Map<String, String> mDistrictMapIds = new HashMap<String, String>();

    /**
     * 当前省的名称
     */
    protected String mCurrentProviceName;
    protected String mCurrentProviceNameIds;
    /**
     * 当前市的名称
     */
    protected String mCurrentCityName;
    protected String mCurrentCityNameIds;
    /**
     * 当前区的名称
     */
    protected String mCurrentDistrictName = "";
    protected String mCurrentDistrictNameIds = "";

    /**
     * 当前区的邮政编码
     */
    protected String mCurrentZipCode = "";


    /**
     * common/api/getAll数据
     */
    protected void initProvinceDatas() {

        //*/ 初始化默认选中的省、市、区
        if (provinceList != null && !provinceList.isEmpty()) {
            mCurrentProviceName = provinceList.get(0).getAreaName();
            mCurrentProviceNameIds = provinceList.get(0).getAreaId();
            List<CityModel> cityList = provinceList.get(0).getChildern();
            if (cityList != null && !cityList.isEmpty()) {
                mCurrentCityName = cityList.get(0).getAreaName();
                mCurrentCityNameIds = cityList.get(0).getAreaId();
                List<DistrictModel> districtList = cityList.get(0).getChildern();
                if (districtList.size() > 0) {
                    mCurrentDistrictName = districtList.get(0).getAreaName();
                    mCurrentDistrictNameIds = districtList.get(0).getAreaId();
                } else {
                    mCurrentDistrictName = "";
                    mCurrentDistrictNameIds = "";
                }
            }
        }
        //*/
        if (provinceList != null && !provinceList.isEmpty()) {
            mProvinceDatas = new String[provinceList.size()];
            mProvinceDataIds = new String[provinceList.size()];
            for (int i = 0; i < provinceList.size(); i++) {
                // 遍历所有省的数据
                mProvinceDatas[i] = provinceList.get(i).getAreaName();
                mProvinceDataIds[i] = provinceList.get(i).getAreaId();
                List<CityModel> cityList = provinceList.get(i).getChildern();
                String[] cityNames = new String[cityList.size()];
                String[] cityNameIds = new String[cityList.size()];
                for (int j = 0; j < cityList.size(); j++) {
                    // 遍历省下面的所有市的数据
                    cityNames[j] = cityList.get(j).getAreaName();
                    cityNameIds[j] = cityList.get(j).getAreaId();
                    List<DistrictModel> districtList = cityList.get(j).getChildern();
                    String[] distrinctNameArray = new String[districtList.size()];
                    String[] distrinctNameArrayIds = new String[districtList.size()];
                    DistrictModel[] distrinctArray = new DistrictModel[districtList.size()];
                    for (int k = 0; k < districtList.size(); k++) {
//                                // 遍历市下面所有区/县的数据
                        DistrictModel districtModel = new DistrictModel(districtList.get(k).getAreaName(), districtList.get(k).getAreaId());
                        // 区/县对于的邮编，保存到mZipcodeDatasMap
//                                mZipcodeDatasMap.put(districtList.get(k).getAreaName(), districtList.get(k).getAreaId());
                        distrinctArray[k] = districtModel;
                        distrinctNameArray[k] = districtModel.getAreaName();
                        distrinctNameArrayIds[k] = districtModel.getAreaId();
                        mDistrictMapIds.put(districtList.get(k).getAreaName(), districtList.get(k).getAreaId());

                    }
                    // 市-区/县的数据，保存到mDistrictDatasMap
                    mDistrictDatasMap.put(cityNames[j], distrinctNameArray);
                    mDistrictDatasMapIds.put(cityNameIds[j], distrinctNameArrayIds);
                }
                // 省-市的数据，保存到mCitisDatasMap
                mCitisDatasMap.put(provinceList.get(i).getAreaName(), cityNames);
                mCitisDatasMapIds.put(provinceList.get(i).getAreaId(), cityNameIds);
            }
        }
    }


    private class NumberAdapter extends BaseAdapter {
        int mHeight = 50;
        String[] mData = null;
        String[] mDataIds = null;

        public NumberAdapter(String[] data, String[] dataIds/*,String mIds*/) {
            mHeight = (int) Utils.dipToPx(context, mHeight);
            this.mData = data;
            this.mDataIds = dataIds;
        }

        @Override
        public int getCount() {
//            return (null != mData) ? mData.length : 0;
            return (mData == null) ? 0 : mData.length;
        }

        @Override
        public View getItem(int position) {
            return getView(position, null, null);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public void setData(String[] mData, String[] dataIds/*,String mIds*/) {
            this.mData = mData;
            this.mDataIds = dataIds;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            WheelTextView textView = null;

            if (null == convertView) {
                convertView = new WheelTextView(context);
                convertView.setLayoutParams(new TosGallery.LayoutParams(-1, mHeight));
                textView = (WheelTextView) convertView;
                textView.setTextColor(ContextCompat.getColor(context, R.color.black_3));
                textView.setTextSize(20);
                textView.setGravity(Gravity.CENTER);
            }
            String text = mData[position];
            if (null == textView) {
                textView = (WheelTextView) convertView;
            }
            textView.setText(text);
            return convertView;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            dismiss();
        }
        return super.onKeyDown(keyCode, event);
    }
}
